from ylTDX2 import * #from ylTDX import all def function
import time
import tushare as ts
import datetime
from backtesting import Backtest, Strategy
import datetime
# from zhuang_jia_xi_chou import *
# import numpy as np
# import mplfinance as mpf
# import os
# from  chinese_calendar  import is_holiday
# from backtesting.test import SMA, GOOG
# from matplotlib.pyplot import savefig
# from numpy import flatiter, left_shift, nan
# from numpy.lib.function_base import append
# import pandas as pd
# from backtesting.lib import crossover

ts.set_token("6667cd4a2326f2f937062a0f4fb59aea5c56d13b1f6f26225f115fe9")

def return_df(code):                    
    days=60
    pro = ts.pro_api()
    end_date_str=time.strftime("%Y%m%d")
    end_datetime = datetime.datetime.strptime(end_date_str, '%Y%m%d') 
    start_datetime=n_days_before(end_datetime,days)
    start_date_str=start_datetime.strftime("%Y%m%d")
    try:
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)       
    except Exception as e:
        print(e)
        time.sleep(60) 
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)
    df['date'] = df['trade_date'].map(lambda ts_date: datetime.datetime.strptime(ts_date,'%Y%m%d') )
    df.set_index('date',inplace=True)
    df.sort_index(inplace=True)  
    df.drop(columns=['trade_date'],inplace=True)
    df.rename(columns={'open': 'Open','high': 'High','low': 'Low','close': 'Close','vol': 'Volume'},inplace=True) #df.rename(columns={"A": "a", "B": "c"}) 
    df_new=df[["Open","High","Low","Close","Volume"]]
    return df_new

class zjxc(Strategy):
    def init(self):
        # price = self.data.Close
        # self.ma1 = self.I(SMA, price, 10)
        # self.ma2 = self.I(SMA, price, 20)
        # m=54
        # n=34  
        self.df_new=return_df(799)    
        # HIGH=df_new["High"].to_list()  
        CLOSE=self.df_new["Close"].to_list()  
        # LOW=df_new["Low"].to_list()
        # Today=time.strftime("%Y-%m-%d-%H-%M-%S")
        LC=REF(CLOSE,1)
        self.抄=multiply(divide(SMA(MAX(subtraction(CLOSE,LC),0),12,1),SMA(ABS(subtraction(CLOSE,LC)),12,1)),100)
        self.df_new['buy']=[True if i<30 else False for i in self.抄]
        self.df_new['sell']=[True if i>70 else False for i in self.抄]
        self.df_new['buy_sell']=TFILTER(self.df_new['buy'],self.df_new['sell'],0)
        self.df_new.to_csv("bt_cdsz.csv")
        底=30
        神=70
        针=50

    def next(self):
        if self.df_new['buy_sell']:
            self.buy()
        elif self.df_new['sell']:
            self.sell()
        # if crossover(self.ma1, self.ma2):
        #     self.buy()
        # elif crossover(self.ma2, self.ma1):
        #     self.sell()

if __name__=='__main__':
    # print(type(return_df(799).index[0]))
    # bt = Backtest(GOOG, zjxc, commission=.002,
    #               exclusive_orders=True)
    bt = Backtest(return_df(799), zjxc, commission=.002,
                exclusive_orders=True)
    stats = bt.run()
    bt.plot()